//
//  Window.swift
//  ADKit
//
//  Created by Adoma on 2020/10/22.
//

import UIKit

public struct WindowManager {

    public static var keyWindow: UIWindow? {
        
        if let window = UIApplication.shared.delegate?.window {
            return window
        }
        
        if #available(iOS 13, *) {
            
            guard let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene else { 
                return nil
            }
            
            if #available(iOS 15, *) {
                return scene.keyWindow
            }
            
            return scene.windows.first(where: { $0.isKeyWindow })
        }
        
        return nil
    }
    
    public static var currentViewController: UIViewController? {
        
        guard let root = keyWindow?.rootViewController else {
            return nil
        }
        
        func getCurrent(parent: UIViewController?) -> UIViewController? {
            
            guard let parent = parent else {
                return nil
            }
            
            switch parent {
            case let tab as UITabBarController:
                return getCurrent(parent: tab.selectedViewController)
            case let navi as UINavigationController:
                return getCurrent(parent: navi.topViewController)
            default:
                guard let presented = parent.presentedViewController else {
                    return parent
                }
                return getCurrent(parent: presented)
            }
        }
        
        return getCurrent(parent: root)
    }
    
    public static var currentNavigationController: UINavigationController? {
        
        guard let current = currentViewController else {
            return nil
        }
        
        func findNavi(parent: UIViewController?) -> UINavigationController? {
            
            guard let parent = parent else {
                return nil
            }
            
            switch parent {
            case let navi as UINavigationController:
                return navi
            default:
                guard let presenting = parent.presentingViewController else {
                    return findNavi(parent: parent.parent)
                }
                return findNavi(parent: presenting)
            }
        }
        
        return findNavi(parent: current)
    }
}
